package com.kkshop.gwt.widget.wizard.impl;

import java.util.Iterator;
import java.util.Vector;

import com.kkshop.gwt.widget.wizard.Wizard;
import com.kkshop.gwt.widget.wizard.WizardPage;
import com.kkshop.gwt.widget.wizard.WizardWidget;

public abstract class AbstractWizard implements Wizard {

	private WizardWidget wizardWidget;
	protected Vector pages = new Vector();
	protected boolean initialized = false;

	public AbstractWizard() {
	}

	public void addPage(WizardPage page) {
		pages.add(page);
		page.setWizard(this);
	}

	public int getIndexOfPage(WizardPage page) {
		return pages.indexOf(page);
	}

	public WizardPage getNextWizardPage(WizardPage page) {
		int i = page == null ? 0 : pages.indexOf(page) + 1;
		if (i >= pages.size()) {
			return null;
		}
		return (WizardPage) pages.get(i);
	}

	public WizardPage getPrevWizardPage(WizardPage page) {
		if (page == null) {
			return null;
		}
		int i = pages.indexOf(page) - 1;
		if (i < 0) {
			return null;
		}
		return (WizardPage) pages.get(i);
	}

	public WizardPage[] getWizardPages() {
		// this is not supported :((((
		// return (WizardPage[]) pages.toArray(new WizardPage[pages.size()]);

		WizardPage[] pages = new WizardPage[this.pages.size()];
		int i = 0;
		for (Iterator iter = this.pages.iterator(); iter.hasNext();) {
			pages[i++] = (WizardPage) iter.next();
		}
		return pages;
	}

	public boolean canFinish() {
		for (Iterator i = pages.iterator(); i.hasNext();) {
			WizardPage page = (WizardPage) i.next();
			if (!page.canFlipToNextPage()) {
				return false;
			}
		}
		return true;
	}

	public void setWizardWidget(WizardWidget wizardWidget) {
		this.wizardWidget = wizardWidget;
	}

	public WizardWidget getWizardWidget() {
		return this.wizardWidget;
	}
}
